package org.example.service.minio.impl;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.example.model.common.AppHttpCodeEnum;
import org.example.model.common.ResponseResult;
import org.example.model.minio.MinioPojo;
import org.example.service.minio.MinioFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;


/**
 * Minio文件管理
 */
@Service
public class MinioFileServiceImpl implements MinioFileService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioPojo minioPojo;

    /**
     * 上传文件
     */
    @Override
    public ResponseResult<String> UploadFile(MultipartFile file) {
        ResponseResult<String> result = new ResponseResult<>();
        try {
            String bucketName = minioPojo.getBucketName();
            //判断桶是否存在
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!bucketExists) {
                //不存在就创建一个桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            String currentDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String uuid = UUID.randomUUID().toString();
            String fileName = currentDate + "/" + uuid + "/" + file.getOriginalFilename();
            minioClient
                    .putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType()).build());
            String filePath = minioPojo.getUrl() + "/" + bucketName + "/" + fileName;
            result.ok(AppHttpCodeEnum.IMAGE_UPLOAD_SUCCESS.getCode(), filePath, AppHttpCodeEnum.IMAGE_UPLOAD_SUCCESS.getErrorMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.error(AppHttpCodeEnum.IMAGE_UPLOAD_ERROR.getCode(), AppHttpCodeEnum.IMAGE_UPLOAD_ERROR.getErrorMessage());
            return result;
        }
    }
}


